package zx.lrn.notes.basic_grammer.internal_class;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: AnonymousInternalClass
 * @Description: 匿名内部类
 * @Author: zhaoxuan
 * @Date: 2020/2/29 23:50
 **/
public class AnonymousInternalClass {
    private int age;

    public void peopleSay(String name, int birthYear) {
        /**
         * 匿名内部类用以一次性的实现接口或抽象类，该实现类没有名称，不可复用，JDK1.8之前常用作传递代码块之用，但现在已被lambda替代, 匿名内部类访问外围类的属性语法与其他内部类一致。
         */
        Person person = new Person(name) {
            @Override
            public void say() {
                System.out.println(this.getClass());
                System.out.println(
                    "name = " + name + ",age = " + AnonymousInternalClass.this.age + ",birthYear = " + birthYear);
            }
        };
        person.say();
    }

    public static void main(String[] args) {
        AnonymousInternalClass anonymousInternalClass = new AnonymousInternalClass();
        anonymousInternalClass.peopleSay("XX", 18);

        // 利用匿名内部类的技巧直接构建List，外层大括号代表匿名子类，内层大括号是初始代码块
        List<String> list = new ArrayList<String>() {
            {
                add("a");
                add("b");
                add("c");
            }
        };
        System.out.println(list);
    }
}

abstract class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public abstract void say();
}
